"""
用户模型
作者：资深Flask讲师
功能：用户表定义，包含用户信息和角色信息
"""

from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from myflask.tools.bd import db


class User(db.Model):
    """
    用户表
    包含：基本信息、角色信息、部门信息
    """
    __tablename__ = 'users'
    
    # 基本字段
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='用户ID')
    user = db.Column(db.String(50), unique=True, nullable=False, comment='用户账号')
    password = db.Column(db.String(255), nullable=False, comment='密码（加密存储）')
    
    # 角色字段：admin-超级管理员, manager-部门经理, employee-普通员工
    role = db.Column(db.String(20), nullable=False, default='employee', comment='角色：admin/manager/employee')
    
    # 部门字段（部门经理和普通员工需要关联部门）
    department_id = db.Column(db.Integer, db.ForeignKey('departments.id'), nullable=True, comment='所属部门ID')
    
    # 扩展字段
    real_name = db.Column(db.String(50), nullable=True, comment='真实姓名')
    email = db.Column(db.String(100), nullable=True, comment='邮箱')
    phone = db.Column(db.String(20), nullable=True, comment='手机号')
    status = db.Column(db.Integer, default=1, comment='状态：1-正常，0-禁用')
    
    # 时间字段
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关系
    department = db.relationship('Department', backref='users', lazy=True)
    
    def set_password(self, password):
        """设置密码（加密存储）"""
        self.password = generate_password_hash(password)
    
    def check_password(self, password):
        """验证密码"""
        return check_password_hash(self.password, password)
    
    def to_dict(self, include_department=True):
        """转换为字典（用于API返回）"""
        data = {
            'id': self.id,
            'user': self.user,
            'role': self.role,
            'role_name': self.get_role_name(),
            'department_id': self.department_id,
            'real_name': self.real_name,
            'email': self.email,
            'phone': self.phone,
            'status': self.status,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
        }
        
        # 包含部门信息
        if include_department and self.department:
            data['department_name'] = self.department.name
        
        return data
    
    def get_role_name(self):
        """获取角色中文名称"""
        role_map = {
            'admin': '超级管理员',
            'manager': '部门经理',
            'employee': '普通员工'
        }
        return role_map.get(self.role, '未知角色')
    
    def is_admin(self):
        """是否是超级管理员"""
        return self.role == 'admin'
    
    def is_manager(self):
        """是否是部门经理"""
        return self.role == 'manager'
    
    def is_employee(self):
        """是否是普通员工"""
        return self.role == 'employee'
    
    def __repr__(self):
        return f'<User {self.user}>'

